package bot {

import java.io.IOException;
import javax.servlet.http._;
import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;
import java.util.logging.Logger;

//@SuppressWarnings({ "serial" })
class BotServlet extends HttpServlet {
    override def doPost(req: HttpServletRequest, res: HttpServletResponse)
          /* throws IOException */ {
        var xmpp: XMPPService = XMPPServiceFactory.getXMPPService();
        var message: Message = xmpp.parseMessage(req);
        
        processMessage(req, message);
    }
    
    def processMessage(req: HttpServletRequest, message: Message) = {
        val fromJid: JID = message.getFromJid()
        val url = req.getRequestURL().toString()
        if (url.contains("ou-chat") && !fromJid.toString().contains("j_blom@studie.ou.nl")) {
        	sendMessage(fromJid, "Deze chat, ou-chat@appspot.com is niet langer in gebruik.")
        	sendMessage(fromJid, "De OU chat is verplaatst naar oucafe@appspot.com.")
        }
        
    	if (botShouldServeThis(url, fromJid)) {	    	
	        val body: String = message.getBody();
	        val isRegistering = messageIsRegisterCommand(message)
	        ConnectionHandler.logInfo("message from " + fromJid + ": " + message.getBody());
	        if (UserManager.isRegistered(message.getFromJid()) || isRegistering) {
	        	if (!isRegistering) {
	        		UserManager.setLastActive(fromJid.toString())
	        	}
	        	if (body.startsWith("/") || body.startsWith(")")) {
	        		processCommand(body, message);
	        	}
	        	else {
	        		ConnectionHandler.processPublicMessage(message);
	        	}
	        }
	        else {
	        	sendMessage(fromJid, "_You are not registered. To use this chat bot you must register_")
	        	sendMessage(fromJid, "_Use the /register command to register:_")
	        	CommandHandler.sendRegisterHelp(fromJid)
	        }
    	}
    }
    
    def processCommand(command: String, message: Message) = {
    	val words: Array[String] = command.split("[ \t]+");

    	val handlerStatus = CommandHandler.handle(words, message);
    	if (!handlerStatus.equals("ok")) {
    		// command was not handled properly, inform user
    		sendMessage(message.getFromJid(), "Command '" + words(0) + "': " + handlerStatus);
    	}
    }   	
 
    /*
     * convenience method for ConnectionHandler.sendMessage()
     */
    def sendMessage(jid: JID, msg: String) = {
    	ConnectionHandler.sendMessage(jid, msg, true);
    }
    
    def messageIsRegisterCommand(message: Message) : Boolean = {
    	return message.getBody().substring(1).startsWith("register")
    }
    
    private def autoRegister(fromJid: JID) = {
    	var nick = ""
		UserManager.addUser(fromJid, nick)
		nick = UserManager.getNick(fromJid.toString())
		// TODO: find out why nick isn't displayed when default (name part of email)
		sendMessage(fromJid, ChatUser.jid2email(fromJid) + " automatically registered as '" + nick + "'")
		sendMessage(fromJid, "You can undo this registration with /unregister .")
		sendMessage(fromJid, "But please not that any next message to this chatbot")
		sendMessage(fromJid, "will automatically register you again")
		autoJoin(fromJid)
    }
    
    private def autoJoin(fromJid: JID) = {
		UserManager.setOnline(fromJid, true, "autojoined")
    }
    
    private def botShouldServeThis(url: String, jid: JID) : Boolean = {
    	if (url.contains("ou-chat") || url.contains("oucafe")) {
    		return (jid.toString().contains("@studie.ou.nl") ||
    			jid.toString.contains("@studie.openuniversiteit.be"))
    	}
    	
    	return true
    }
}

object BotServlet {
	var doLog: Boolean = true
	
        def setLogging(set: Boolean) {
    	doLog = set
    }
    
    def logInfo(msg: String) = {
    	if (doLog) {
    		var log: Logger = Logger.getLogger("bot.BotServlet")
    		log.info(msg)
    	}
    }

    def logWarn(msg: String) = {
    	if (doLog) {
    		var log: Logger = Logger.getLogger("bot.BotServlet")
    		log.warning(msg)
    	}
    }

	
}

} // package bot
